import { onMounted, onUnmounted, ref, Ref } from 'vue'

// 点击外侧
const useClickOutside = (elementRef: Ref<null | HTMLElement>, isOpen: Ref<boolean>): Ref<boolean> => {
  const isClickOutside = ref(false)
  const handler = (e: MouseEvent) => {
    if (!elementRef.value) return
    // 打开状态下且点击元素在目标元素外
    if (isOpen.value && !elementRef.value.contains(e.target as HTMLElement)) {
      isClickOutside.value = true
    } else {
      isClickOutside.value = false
    }
  }
  onMounted(() => {
    document.addEventListener('click', handler)
  })
  onUnmounted(() => {
    document.removeEventListener('click', handler)
  })
  return isClickOutside
}

export default useClickOutside
